package xyz.yiui.servlet.user;

import xyz.yiui.pojo.User;
import xyz.yiui.service.user.UserService;
import xyz.yiui.service.user.UserServiceImpl;
import xyz.yiui.util.Constans;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    //控制层，调用业务层代码

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LoginServlet----------start");
        //获取用户名和密码
        String userCode=req.getParameter("userCode");
        String userPassword=req.getParameter("userPassword");
        ///和数据库的密码进行对比，调用业务层
        UserService userService=new UserServiceImpl();
        User user=userService.login(userCode,userPassword);
        ///查询成功，可以登录
        if(user!=null){
            ///将用户的信息放到session
            req.getSession().setAttribute(Constans.USER_SESSION,user);
            ///跳转到主页
            resp.sendRedirect("jsp/frame.jsp");
        }else{
            ///查询失败,转发到登陆页面，提示用户名或密码错误
            req.setAttribute("error","用户名或密码不正确");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
